<!--二级集团检查计划明细 /checkPlanItem-->
<template>
  <Layout>
    <Form ref="queryForm" :model="dataToQuery" :label-width="120">
      <Row class="query-form">
        <Col span="8">
          <FormItem label="企业名称：" prop="order">
            <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyId' :orgTree="true"
                          :currentOrgId="dataToQuery.companyId"
                          :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="参检人员：">
            <Input type='text' v-model='dataToQuery.inspectorsName'></Input>
          </FormItem>
        </Col>
        <Col span="8" v-show="switchFlag">
          <FormItem label='检查日期：' prop='checkTime'>
            <DatePicker class="query-form-el" v-model="dataToQuery.checkTime" type="daterange"
                        placement="bottom-end" placeholder="请选择查询时间段" @on-change="selectCheckTime"></DatePicker>
          </FormItem>
        </Col>
        <Col span="8" v-show="!switchFlag">
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">

        <Col span="8" offset="16">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
          <Button size="large" class="ivu-btn-add" icon="md-home" @click="back">返回</Button>
        </Col>
      </Row>
    </Form>
    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
           :loading='pageStatus.loading' @on-sort-change="sortChange"
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>
    <Modal :title="getModalTitle('二级集团'+(this.planType == '2'?'环保':'安全')+'检查计划明细')" :transfer=false
           :mask-closable="false" v-model="dialogShow"
           v-if="dataToView && dialogShow" :width=800 :styles="{height:'450px'}" class-name='limit-height-dialog'>
      <Row>
        <Col span="24">
          <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':'modal-form'" :show-message="false"
                :model="dataToView" :rules="mode === 'view'?{} :ruleCustom"
                :label-position="mode === 'view'?'right':'top'" :label-width="mode === 'view'?160:null">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='被检查单位：' prop='companyId'>
                  <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                  <cascader-dom v-else ref='orgCascader'
                                @setOrgInfo='setCompanyId'
                                @setOrgname="setCompanyName"
                                :orgTree="true"
                                :currentOrgId="dataToView.companyId"
                                :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}"
                  ></cascader-dom>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='检查日期：' prop='checkTime'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.checkTime) }}</div>
                  <DatePicker v-else :options="options" class="w" :transfer="true" placeholder="请选择检查日期"
                              v-model='dataToView.checkTime'></DatePicker>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='参检人员：' prop='inspectorsId'>
                  <div v-if="mode === 'view'">{{ dataToView.inspectorsName }}</div>
                  <Input v-else class='' placeholder="请填写参检人员" type="textarea"
                         @on-focus="()=>this.$refs['userDom'].openOrgModal()" readonly
                         v-model='dataToView.inspectorsName'></Input>

                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='重点检查内容：' prop='checkContent'>
                  <div v-if="mode === 'view'">{{ dataToView.checkContent }}</div>
                  <Input v-else class='' show-word-limit :maxlength="1024" placeholder="请填写重点检查内容"
                         :autosize="{minRows: 2,maxRows: 5}" type='textarea' v-model='dataToView.checkContent'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='备注：' prop='remark'>
                  <div v-if="mode === 'view'">{{ dataToView.remark }}</div>
                  <Input v-else class='' show-word-limit :maxlength="1024" placeholder="请填写备注"
                         :autosize="{minRows: 2,maxRows: 5}" type='textarea' v-model='dataToView.remark'></Input>
                </FormItem>
              </Col>
            </Row>

            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='填表人：' prop='createUserName'>
                  <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                  <Input v-else type='text' v-model='dataToView.createUserName' readonly></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='填表时间：' prop='createUserName'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                  <DatePicker v-else type="date" placeholder="请选择日期" class="w" v-model='dataToView.createDate'
                              readonly></DatePicker>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定</Button>
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
        <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
      </div>
    </Modal>
    <userDom ref="userDom"
             :isButton="true"
             :singleChoice=false
             :ifUser="true"
             @setData="setInspectors"
             :selectData="checkUsers"></userDom>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {sessionStorage} from '@/common/cacheUtils.js';
import pageCommonFunction from '@/components/pageCommonFunction.js'
import userDom from '@/components/input-user.vue'

var cascaderDom = () => import('@/components/cascader-dom.vue');
export default {
  components: {
    cascaderDom, userDom
  },
  data() {
    return {
      ...this.createCommonDataField(),
      columns1: [
        {title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRender},
        {key: 'companyName', title: '被检查单位', align: 'center', minWidth: 150},
        {
          key: 'checkTime',
          title: '检查日期',
          sortable: "custom",
          align: 'center',
          minWidth: 120,
          render: this.renderCellDate
        },
        {key: 'checkContent', title: '重点检查内容', align: 'center', minWidth: 150, tooltip: true},
        {key: 'inspectorsName', title: '参检人员', align: 'center', minWidth: 150, tooltip: true},
        {key: 'createUserName', title: '填报人', align: 'center', minWidth: 120},
        {
          key: 'createDate',
          title: '填报时间',
          sortable: "custom",
          align: 'center',
          minWidth: 120,
          render: this.renderCellDate
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 160,
          align: 'center',
          render: (h, params) => {
            if (this.currentUser.loginId === this.Common.admin) {
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.viewData(params);
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  disabled: true,
                  style: {fontSize: '14px'},
                  on: {
                    click: () => {
                      this.editData(params);
                    }
                  }
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: 'red'},
                  on: {
                    click: () => {
                      this.deleteData(params);
                    }
                  }
                }, '删除')
              ]);
            }
            if (this.comparDate(params.row.checkTime)) {
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.viewData(params);
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '删除')
              ]);
            }
            if (this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
            ||this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) {
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.viewData(params);
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  disabled: true,
                  style: {fontSize: '14px'},
                  on: {
                    click: () => {
                      this.editData(params);
                    }
                  }
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: 'red'},
                  on: {
                    click: () => {
                      this.deleteData(params);
                    }
                  }
                }, '删除')
              ]);
            } else {
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.viewData(params);
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '删除')
              ]);
            }
          }
        }
      ],
      ruleCustom: {
        companyId: [{required: true, message: '请填写被检查单位', trigger: 'change',}],
        checkTime: [{required: true, message: '请填写检查日期', trigger: 'change', type: 'date'}],
        checkContent: [{required: true, message: '请填写重点检查内容', trigger: 'change',}],
        inspectorsId: [{required: true, message: '请填写参检人员', trigger: 'change',}],
      },
      options: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      },
      checkUsers: [],
      parentId: this.$route.query.id,
      planType: this.$route.query.planType,
      twoLevel: [],
      tableHeight: 10,
      // api
      queryUrl: Api.queryCheckPlanItemUrl,
      deleteUrl: Api.deleteCheckPlanItemUrl,
      updateUrl: Api.updateCheckPlanItemUrl,
      saveUrl: Api.saveCheckPlanItemUrl,
    }
  },
  mounted() {
    let dat = new Date(this.planDate)
    console.log(dat)
    this.setTableHeight();
    this.query();
  },
  methods: {
    ...pageCommonFunction,
    deleteData(params) {
      this.deleteDateAjax(params);
    },
    selectCheckTime(date) {
      this.dataToQuery.checkTime = [this.renderViewDate(date[0]), this.renderViewDate(date[1])]
    },
    openSelectUser() {
      this.$refs['buttonUser'].openOrgModal();
    },
    toPath(params) {
      this.$router.push({path: '/checkPlanItem', query: {id: params.row.id}});
    },

    comparDate(dateValue) {
      return new Date().getTime() >= new Date(dateValue).getTime() + 3600 * 1000 * 24;
    },
    query() {
      this.dataToQuery.parentId = this.parentId;
      if (!this.dataToQuery.checkTime || (!this.dataToQuery.checkTime[0] && !this.dataToQuery.checkTime[1])) {
        this.dataToQuery.checkTime = [];
      }
      this.queryAjax();
    },
    submit(name) {
      this.submitAjax(name);
    },
    afterDataToViewInit(data) {
      this.checkUsers = [];
      if (this.dataToView.inspectorsId) {
        let inspectorsNames = this.dataToView.inspectorsName.split(",");
        let inspectorsIds = this.dataToView.inspectorsId.split(",");
        for (let i = 0; i < inspectorsIds.length; i++) {
          this.checkUsers.push({userId: inspectorsIds[i], name: inspectorsNames[i]})
        }
      }
      this.$nextTick(() => {
        this.$refs.userDom.setCurrentInfo();
      })
    },
    createEmptyDataToAdd() {
      this.checkUsers = [];
      this.$nextTick(() => {
        this.$refs.userDom.setCurrentInfo();
      })
      return {
        parentId: this.parentId,
        twoLevelOrgId: sessionStorage('userId').getObject('userId').twoLevelOrgId,
        checkTime: this.getDate(new Date(), 1),
      }
    },
    back() {
      this.$router.push({path: 'checkPlan', query: {planType: this.planType}})
    },
    setInspectors(data) {
      // this.dataToView.inspectorsName
      let userNames = "";
      let userIds = "";
      data.forEach(user => {
        userNames += user.name + ","
        userIds += user.userId + ","
      })
      this.$set(this.dataToView, 'inspectorsName', userNames.substring(0, userNames.length - 1))
      this.$set(this.dataToView, 'inspectorsId', userIds.substring(0, userIds.length - 1))
    },
    isLastDay(inputDate) {
      debugger;
      var d = new Date(inputDate.replace(/\-/, "/ "));
      var nd = new Date(d.getTime() + 24 * 60 * 60 * 1000); //next day
      console.log(d.getFullYear());
      console.log(nd.getFullYear());
      if (d.getFullYear() != nd.getFullYear())
        return true;

      return (d.getMonth() != nd.getMonth())

    },
    getDate(date, i) {
      if (date === undefined || date === null) {
        date = new Date();
      }
      if (this.isLastDay(this.renderViewDate(date))) {
        return date;
      }
      let month, day;
      date.setTime(date.getTime() + i * 24 * 60 * 60 * 1000);
      month = date.getMonth() + 1 < 10 ? '0' + parseInt(date.getMonth() + 1) : date.getMonth() + 1;
      day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
      return date.getFullYear() + "-" + month + "-" + day;
    },
    getFirstDay(date) { //当前月第一天
      if (date) {
        date = new Date(date);
      } else {
        date = new Date();
      }

      var y = date.getFullYear(); //获取年份
      var m = date.getMonth() + 1; //获取月份
      var d = '01';
      m = m < 10 ? '0' + m : m; //月份补 0

      return new Date([y, m, d].join("-"))
    },
    getLastDay(date) { //当前月最后一天
      if (date) {
        date = new Date(date);
      } else {
        date = new Date();
      }

      var y = date.getFullYear(); //获取年份
      var m = date.getMonth() + 1; //获取月份
      var d = date(y, m, 0).getDate(); //获取当月最后一日
      m = m < 10 ? '0' + m : m; //月份补 0
      d = d < 10 ? '0' + d : d; //日数补 0

      return new Date([y, m, d].join("-"))
    },
  },
  watch: {},

}
</script>

<style lang='css' scoped>

</style>
